package com.beauty.dressing.module.main.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beauty.dressing.R;
import com.beauty.dressing.common.base.BaseActivity;
import com.beauty.dressing.common.bean.Ad;
import com.beauty.dressing.common.bean.BaseBean;
import com.beauty.dressing.common.bean.Post;
import com.beauty.dressing.common.bean.SearchHistory;
import com.beauty.dressing.common.bean.SearchHotBean;
import com.beauty.dressing.common.utils.ResUtil;
import com.beauty.dressing.logic.control.LBController;
import com.beauty.dressing.module.common.view.BannerLayout;
import com.beauty.dressing.module.main.adapter.HotAdapter;
import com.beauty.dressing.module.main.adapter.PostsSearchAdapter;
import com.framework.common.utils.IKeyboardUtils;
import com.framework.common.utils.INetworkUtils;
import com.framework.common.utils.IStringUtil;
import com.framework.common.view.pulltorefresh.PullToRefreshBase;
import com.framework.library.haorefresh.HaoRecyclerView;
import com.framework.library.haorefresh.ProgressView;
import com.xiaolanba.commonlib.fresco.FrescoUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * v3.5 帖子搜索
 * @author Angus
 * @company 9zhitx.com
 */
public class PostSearchActivity extends BaseActivity {

	/**
	 * 粉圈帖子搜索
	 */
	public static final int SEARCH_POSTS = 4;

	private LinearLayout mHistoryLayout;
	private HaoRecyclerView mRecyclerView;
	private View mNoDataLayout;
	private TextView mNoDataTxt;
	private AutoCompleteTextView mInputEt;
	private TextView mSearchTxt;
	private ImageView mClearBtn;

	private PostsSearchAdapter mAdapter;
	private String searchName;

	private List<SearchHistory> mHistoryList = new ArrayList<SearchHistory>();
//	private ListView mHistoryListView;
	private LinearLayout mHotSearchLayout;//热门搜索
//    private AutoCompleteAdapter mHistoryAdapter;
    /** 是否监听输入框 */
    private boolean mBlockCompletion = true;
	private int type = SEARCH_POSTS;
	private long pageNo = 1;
	private View mTopSpace;
	private GridView mHotGridview;
	private boolean delayHotwordWhenSearching = false;
    BannerLayout bannerLayout ;
    private String keyword;
	/**
	 * 搜索明星
	 * @param mContext
	 */
	public static void startActivity(Context mContext, String keyword){
		Intent intent = new Intent(mContext, PostSearchActivity.class);
		intent.putExtra("keyword", keyword);
		mContext.startActivity(intent);
	}

	@Override
	public void setContentView() { //这里只负责搜索帖子和圈子
		Intent intent = getIntent();
		if (null != intent) {
			keyword = intent.getStringExtra("keyword");
		}
		setContentView(R.layout.activity_post_search_layout);
	}

	@Override
	public void findView() {
		findViewById(R.id.left_btn).setOnClickListener(this);
        bannerLayout = new BannerLayout(context);
        mSearchTxt = (TextView)findViewById(R.id.search_text);
        mSearchTxt.setOnClickListener(this);
        mSearchTxt.setEnabled(false);

        mInputEt = (AutoCompleteTextView) findViewById(R.id.input_et);
        mClearBtn = (ImageView) findViewById(R.id.search_clear);
        mClearBtn.setOnClickListener(this);

		mHistoryLayout = (LinearLayout) findViewById(R.id.search_history_layout);
		mInputEt.requestFocus();
        mInputEt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!mBlockCompletion) return;

//				mHistoryAdapter.getFilter().filter(s, new Filter.FilterListener() {
//					@Override
//					public void onFilterComplete(int count) {
//						if (count > 0) {
//							mHistoryLayout.setVisibility(View.GONE);
//							hideHotSearchLayout();
//							mHistoryListView.setVisibility(View.VISIBLE);
//						} else {
//							mHistoryListView.setVisibility(View.GONE);
//						}
//					}
//				});
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!mBlockCompletion) return;

				String name = mInputEt.getText().toString().trim();
				if (!IStringUtil.isEmpty(name)) {
					mClearBtn.setVisibility(View.VISIBLE);
					mSearchTxt.setEnabled(true);
				} else {
					mClearBtn.setVisibility(View.GONE);
					mSearchTxt.setEnabled(false);
					closeHistory();
					mNoDataLayout.setVisibility(View.GONE);//TODO
					mAdapter.clearAllList();
//					mAdapter.notifyDataSetChanged();
					mHistoryLayout.setVisibility(View.VISIBLE);
					showHotSearchlayout();
				}
			}
		});

        //监听键盘上的搜索键
        mInputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					search(mInputEt.getText().toString().trim());
				}
				return false;
			}
		});

		mRecyclerView = (HaoRecyclerView) findViewById(R.id.recyclerview);
		mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
		mAdapter = new PostsSearchAdapter(context);
		mAdapter.addHeaderView(bannerLayout);
		mRecyclerView.setItemAnimator(null);
		mRecyclerView.setAdapter(mAdapter);
		mRecyclerView.addOnScrollListener(FrescoUtil.getPauseOnScrollListener());
		mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
			@Override
			public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
				int position = parent.getChildAdapterPosition(view);
				if (position == 0) {
					outRect.left = 0;
					outRect.right = 0;
					outRect.top = 1; // header 隐藏时给点高度，防止不能下拉
				}
			}
		});

		mNoDataLayout = findViewById(R.id.no_data_layout);
		mNoDataTxt = (TextView)findViewById(R.id.no_data_txt);
		mNoDataLayout.setVisibility(View.GONE);
		mNoDataLayout.setOnClickListener(this);

//        mHistoryListView = (ListView)findViewById(R.id.history_listview);
//        mHistoryListView.setOnItemClickListener(this);
        mHotSearchLayout = (LinearLayout) findViewById(R.id.hot_search_layout);
		mInputEt.setHint(R.string.post_search_hint);
		mHotGridview = (GridView) this.findViewById(R.id.hot_gridview);
		mTopSpace = this.findViewById(R.id.top_space_view);

		ProgressView progressView = new ProgressView(context);
		progressView.setIndicatorId(ProgressView.BallPulse);
		progressView.setIndicatorColor(ResUtil.getColor(R.color.theme_blue));
		mRecyclerView.setFootLoadingView(progressView);
		TextView textView = new TextView(context);
		textView.setText("全部加载完成");
		mRecyclerView.setFootEndView(textView);
		mRecyclerView.loadMoreEnd();
	}


	@Override
	public void initData() {
//		mHistoryAdapter = new AutoCompleteAdapter(this,mHistoryList);
//		mHistoryListView.setAdapter(mHistoryAdapter);
		readHistoryList();
		requestHotSearch();
		List<SearchHotBean> searchList = new ArrayList<>();
		searchList.add(new SearchHotBean("眉毛"));
		searchList.add(new SearchHotBean("眼睛"));
		searchList.add(new SearchHotBean("鼻子"));
		initHotLayout(searchList);
		if (keyword != null){
			mInputEt.setText(keyword);
			LBController.MainHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					search(keyword);
				}
			}, 500);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	/**
	 * 搜索
	 */
	private void search(String name){
		if (IStringUtil.isEmpty(name)) {
			showToast(R.string.input_content);
            mInputEt.requestFocus();
			return ;
		}
		mClearBtn.setVisibility(View.VISIBLE);
		if (name.length() > 25 ) {
			showToast(R.string.input_content_length);
            mInputEt.requestFocus();
            mInputEt.setSelection(mInputEt.getText().length());
            return;
		}
		
		mBlockCompletion = false;
		searchName = name;
		mInputEt.setText(name);
		mInputEt.setSelection(mInputEt.getText().length());
		mBlockCompletion = true;
        mSearchTxt.setEnabled(true);
        
        IKeyboardUtils.closeKeybord(this);
        closeHistory();
        
        //搜索记录保存到数据库
//        controller.getDaoManager().getDaoSession().getSearchHistoryDao().insert(name,type);
        readHistoryList();
        showProgressDialog();
		queryData(false,name,0,1);
	}
	
	private void closeHistory(){
		 //关闭下拉框
        if (mInputEt.isPopupShowing()) {
            mInputEt.dismissDropDown();
        }
        
        //隐藏历史记录列表，显示内容页
//        mHistoryListView.setVisibility(View.GONE);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_btn:
			finish();
			break;
		case R.id.search_clear:
			mInputEt.setText("");
			mClearBtn.setVisibility(View.GONE);
			closeHistory();
			mNoDataLayout.setVisibility(View.GONE);//TODO
			mAdapter.clearAllList();
//			mAdapter.notifyDataSetChanged();
			mHistoryLayout.setVisibility(View.VISIBLE);
			showHotSearchlayout();
			IKeyboardUtils.openKeybord(context,mInputEt);
			break;
		case R.id.search_text:
			search(mInputEt.getText().toString().trim());
			break;
		case R.id.no_data_layout:
			if (!INetworkUtils.getInstance().isNetworkAvailable()){
				showToast(R.string.no_network_to_remind);
				return;
			}
			mNoDataLayout.setVisibility(View.GONE);
			showProgressDialog();
			break;
		default:
			break;
		}
	}
	
	/**
     * 更新搜索记录表
     */
    private void readHistoryList(){
        if (mHistoryList != null) {
//        	List<SearchHistory> historyList = controller.getDaoManager().getDaoSession().getSearchHistoryDao().query(type);
//            if (historyList != null && !historyList.isEmpty()){
//            	mHistoryList.clear();
//                mHistoryList.addAll(historyList);
//                mHistoryAdapter.notifyDataSetChanged();
//            }
//
//			if (historyList != null && historyList.size() > 0) {
//				if (historyList.size() > 3) {
//					historyList = historyList.subList(0, 3);
//				}
//
//				mHistoryLayout.removeAllViews();
//				for (final SearchHistory searchHistory : historyList) {
//					final View view = LayoutInflater.from(context).inflate(R.layout.search_history_item2, null);
//					TextView nameTxt = (TextView) view.findViewById(R.id.name_txt);
//					ImageView deleteImg = (ImageView) view.findViewById(R.id.delete_img);
//					nameTxt.setText(searchHistory.keyword);
//					deleteImg.setOnClickListener(new View.OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							YaYaController.getInstance().getDaoManager().getDaoSession().
//									getSearchHistoryDao().delete(searchHistory.keyword, type);
//
//							mHistoryLayout.removeView(view);
//							readHistoryList();
//						}
//					});
//					view.setOnClickListener(new View.OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							search(searchHistory.keyword);
//						}
//					});
//
//					mHistoryLayout.addView(view);
//				}
//				//最后添加一个清除搜索记录的view
//				View view = LayoutInflater.from(context).inflate(R.layout.search_history_item2, null);
//				view.findViewById(R.id.name_txt).setVisibility(View.GONE);
//				view.findViewById(R.id.delete_img).setVisibility(View.GONE);
//				view.findViewById(R.id.line_view).setVisibility(View.GONE);
//				view.findViewById(R.id.search_clear).setVisibility(View.VISIBLE);
//				view.setOnClickListener(new View.OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						showSureClearSearchDialog(type);
//					}
//				});
//				mHistoryLayout.addView(view);
//				mHistoryLayout.setVisibility(View.VISIBLE);
//			}else{
//				mHistoryLayout.removeAllViews();
//				mHistoryLayout.setVisibility(View.GONE);
//				setTopSpace();
//			}
        }
    }

	/**
	 * 弹出确定清除搜索记录对话框
	 */
	private void showSureClearSearchDialog(final int searchType){
//		if (mSureClearSearchDialog == null){
//			mSureClearSearchDialog = new CommonSureCancelDialog(context,CommonSureCancelDialog.STYLE_CLEAR_SEARCH);
//			mSureClearSearchDialog.setOkClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					clearSearch(searchType);
//					mSureClearSearchDialog.dismiss();
//				}
//			});
//		}
//
//		if (!mSureClearSearchDialog.isShowing()){
//			mSureClearSearchDialog.show();
//		}
	}

	private void clearSearch(int searchType){
//		YaYaController.getInstance().getDaoManager().getDaoSession().getSearchHistoryDao().deleteAll(searchType);
		mHistoryLayout.removeAllViews();
		mHistoryLayout.setVisibility(View.GONE);
		setTopSpace();
		updateHistoryList();
	}

	/**
	 * 更新搜索记录表
	 */
	private void updateHistoryList(){
		if (mHistoryList != null) {
//			List<SearchHistory> historyList = controller.getDaoManager().getDaoSession().getSearchHistoryDao().query(type);
//			if (historyList!=null &&historyList.size()>0){
//				mHistoryList.clear();
//				mHistoryList.addAll(historyList);
//				mHistoryAdapter.notifyDataSetChanged();
//			}
		}
	}

	private void setNoDataLayout(int errorCode){
//		if (mAdapter != null && mAdapter.getPostSize()+mAdapter.getRingSize()>0) {
//			mNoDataLayout.setVisibility(View.GONE);
//			if (errorCode == ErrorCode.CODE_NO_NETWORK){
//                showToast(getString(R.string.no_network_to_remind));
//            }
//		} else {
//			mNoDataLayout.setVisibility(View.VISIBLE);
//			if (errorCode == ErrorCode.CODE_NO_NETWORK) {
//				mNoDataTxt.setText(getResources().getString(R.string.no_net_tip));
//			} else if (errorCode == ErrorCode.CODE_SUCCESS) {
//				mNoDataTxt.setText(getResources().getString(R.string.no_search_tip));
//			} else {
//				mNoDataTxt.setText(getResources().getString(R.string.no_server_tip));
//			}
//		}
	}

	private boolean isRefresh;

	private void queryData(boolean isRefresh , String name, long startIndex, long iorder){
		this.isRefresh = isRefresh;
		clickRingId = -1;
		mHistoryLayout.setVisibility(View.GONE);
		hideHotSearchLayout();
		if(type == SEARCH_POSTS){
//			controller.getServiceManager().getCommunityService().postsSearch(name, pageNo,Constants.PAGE_SIZE,startIndex,
//					isRefresh ? Constants.REFRESH : Constants.LOADMORE,this);
			//请求接口
		}
        mRecyclerView.setVisibility(View.VISIBLE);
		List<BaseBean> list = new ArrayList<>();
		for (int i=0;i<10;i++){
			list.add(new Post());
		}

        mAdapter.setPostList(list);
        List<Ad> adList = new ArrayList<>();
		adList.add(new Ad("http://images.9zhitx.com/a97d8b8b-d703-46c3-9700-b966c8fa7dcb.jpg",null));
		adList.add(new Ad("http://images.9zhitx.com/ac870ecd-26f4-4670-9364-8a542b4e322a.jpg",null));
		adList.add(new Ad("https://tvax2.sinaimg.cn/crop.0.0.664.664.180/006zWmitly8fgxj1jcsevj30ig0igt9h.jpg",null));
        bannerLayout.setBannerPagerAdapter(adList,true);
		dismissProgressDialog();
	}
	
	public void onPullDownToRefresh(PullToRefreshBase refreshView) {
		pageNo = 1;
		queryData(true, searchName, 0, 0);
	}

	public void onPullUpToRefresh(PullToRefreshBase refreshView) {
//		if (mAdapter != null && mAdapter.getPostSize() > 0) {
//			if(type == SEARCH_POSTS){
//				List<BaseBean> list = mAdapter.getPostList();
//				long publishTime = 0;
//				if (list!=null && !list.isEmpty()){
//					Dynamic dynamic = (Dynamic)list.get(list.size() -1);
//					publishTime = dynamic.publishTime;
//				}
//				queryData(false, searchName, publishTime, 0);
//			}
//		}
	}

	public void serviceSuccess(  Object bandObj,
			Object returnObj) {
		if (isFinishing()) return;
		dismissProgressDialog();

	}

	/**
	 * 只需要帖子搜索接口成功时调用
	 */
	private void completeAndCheckNodata(){
	}

	@Override
	public void onPause() {
		super.onPause();
		String brandManu = android.os.Build.BRAND+android.os.Build.MANUFACTURER+"";
		if (brandManu.toLowerCase().contains("samsung")) {//三星手机查看大图后自动弹出输入法bug
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN|
					WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		}
	}

	/***============== 以下是热门搜索的相关逻辑，因为是新加功能暂时与其他方法分开 ================**/
	private HotAdapter mHotAdapter;
	private void initHotLayout(List<SearchHotBean> searchList){
		if (delayHotwordWhenSearching){
			mHotSearchLayout.setVisibility(View.INVISIBLE);
		}else{
			mHotSearchLayout.setVisibility(View.VISIBLE);
		}
		mHotAdapter = new HotAdapter(context);
		if (searchList.size() > 10) {
			mHotAdapter.setList(searchList.subList(0, 10));
		} else {
			mHotAdapter.setList(searchList);
		}
		mHotGridview.setAdapter(mHotAdapter);
		mHotGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (mHotAdapter!= null) {
					SearchHotBean bean = mHotAdapter.getItem(position);
					if (bean!=null){
						search(bean.name);
					}
				}
			}
		});

		mHotGridview.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction()== MotionEvent.ACTION_UP) {
					IKeyboardUtils.closeKeybord(context);
				}
				return false;
			}
		});
		setTopSpace();
	}

	private void requestHotSearch(){
//		controller.getServiceManager().getCommonService().postHotSearchWordTopN(PostRingSearchActivity.this);
		// 热词
	}

	private void hideHotSearchLayout(){
		delayHotwordWhenSearching = true;
		mHotSearchLayout.setVisibility(View.GONE);
	}

	private void showHotSearchlayout(){
		delayHotwordWhenSearching = false;
		if (mHotAdapter!=null && mHotAdapter.getCount()>0) {
			mHotSearchLayout.setVisibility(View.VISIBLE);
			setTopSpace();
            mRecyclerView.setVisibility(View.GONE);
		}
	}

	/**
	 * 调整热门搜索头部的10dp间距，以使看上去更美观
	 */
	private void setTopSpace(){
		if (mHotSearchLayout.getVisibility()== View.VISIBLE){
			if (mHistoryLayout.getVisibility()== View.VISIBLE){
				mTopSpace.setVisibility(View.VISIBLE);
			}else{
				mTopSpace.setVisibility(View.GONE);
			}
		}
	}

	private long clickRingId = -1;

}
